using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using RandomRat.Data;

namespace RandomRat {

	/// <summary>
	/// Summary description for SetsViewer.
	/// </summary>
	public class SetsViewer : System.Windows.Forms.Form {

		const int formWidthWithoutSum = 256;
		const int formSWidthWithSm = 548;

		RndSetsDataSet rndSetsDataSet;
		DataView view;
		CriteriaFormState formState = null;
		ArrayList rndSets = null;

		int _setID = 1;
		int maxSetID = 1;

		bool _viewItemNumber;
		

		#region WINVARS
		
		private System.Windows.Forms.RichTextBox richTextBox1;
		private System.Windows.Forms.GroupBox groupBox1;
		private NumberBox numberBox1;
		private System.Windows.Forms.DataGrid dataGrid1;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.Button butLast;
		private System.Windows.Forms.Button butNext;
		private System.Windows.Forms.Button butBack;
		private System.Windows.Forms.Button butFirst;
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem menuItem7;
		private System.Windows.Forms.MenuItem menuItem8;
		private System.Windows.Forms.MenuItem menFile;
		private System.Windows.Forms.MenuItem menFile_Open;
		private System.Windows.Forms.MenuItem menFile_Print;
		private System.Windows.Forms.MenuItem menFile_PrintPreview;
		private System.Windows.Forms.MenuItem menFile_Close;
		private System.Windows.Forms.MenuItem menView;
		private System.Windows.Forms.MenuItem menView_Summary;
		private System.Windows.Forms.MenuItem menView_ItemNumbers;
		private System.ComponentModel.Container components = null;

		#endregion
		
		public SetsViewer()	{
			InitializeComponent();
			this.rndSetsDataSet = new RndSetsDataSet();
			numberBox1.Text = setID.ToString();
		}

		private bool viewItemNumber {
			get { return _viewItemNumber; }
			set {
				_viewItemNumber = value;
				setUpColums();
			}
		}

		private int setID {
			get { return _setID; }
			set {
				_setID = value;
				validateButtons();
				SyncSetIndx_View();
				numberBox1.Text = value.ToString();
			}
		}

		private void SyncSetIndx_View() {
			view.RowFilter = "SetID = '" + setID + "'";
		}

		private void setUpColums() {
			// Set up colum stuff
			dataGrid1.TableStyles.Clear();

			DataGridTableStyle tableStyle = new DataGridTableStyle();
			tableStyle.DataGrid = dataGrid1;
			tableStyle.MappingName = "SetItems";
			tableStyle.RowHeadersVisible = false;
			

			if (viewItemNumber) {
				DataGridTextBoxColumn column1 = new DataGridTextBoxColumn();
				column1.MappingName = "Slot";
				column1.NullText = "";
				column1.Width = 50;
				tableStyle.GridColumnStyles.Add(column1);
			}

			DataGridTextBoxColumn column2 = new DataGridTextBoxColumn();
			column2.MappingName = "Type";
			column2.NullText = "";

			if (viewItemNumber) {
				column2.Width = 125;
			} else {
				column2.Width = 125 + 50;
			}

			tableStyle.GridColumnStyles.Add(column2);

			dataGrid1.TableStyles.Add(tableStyle);

		}


		public void saveSets(ArrayList rndSets, CriteriaFormState formState, SetsFileType setsFileType) {
			SaveFileDialog saveFileDialog1 = new SaveFileDialog();
 
			if (setsFileType == SetsFileType.Sample) {
				saveFileDialog1.Filter = "RandomRat sample files (*.samp)|*.samp";
			} else if (setsFileType == SetsFileType.Multiple) {
				saveFileDialog1.Filter = "RandomRat sets files (*.sets)|*.sets";
			} else if (setsFileType == SetsFileType.MultipleOrSample) {
				saveFileDialog1.Filter = "RandomRat sets files (*.sets)|*.sets|RandomRat sample files (*.samp)|*.samp";
			}
			
			saveFileDialog1.FilterIndex = 1;
			saveFileDialog1.RestoreDirectory = true ; 
 
			if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
				
				RndSetsDataSet rndSetsDataSet = new RndSetsDataSet();

				DataTable criteria = rndSetsDataSet.Tables["Criteria"];
				DataTable types = rndSetsDataSet.Tables["Types"];
				DataTable patterns = rndSetsDataSet.Tables["Patterns"];


				// Add criteria item
				criteria.Rows.Add(new object[9] {(object)formState.CriteriaID, 
													(object)formState.Slots, 
													(object)formState.Sets, 
													(object)formState.SuccessionTol, 
													(object)formState.EveryOtherTol, 
													(object)formState.checkedSuccessionTol,
													(object)formState.checkedEveryOtherTol,
													(object)formState.checkedPatternRules,
													(object)formState.checkedForceEqualTypes
												});
				
				// Add types
				foreach (string type in formState.Types) {
					types.Rows.Add(new object[2] {(object)formState.CriteriaID, (object)type});
				}

				// Add patterns
				foreach (int[] rule in formState.advancedPatternRules) {
					patterns.Rows.Add(new object[3] {(object)formState.CriteriaID, (object)rule[0], (object)rule[1]});
				}


					
				DataTable sets = rndSetsDataSet.Tables["Sets"];
				DataTable setItems = rndSetsDataSet.Tables["SetItems"];

				for (int i = 0; i < rndSets.Count; i++) {
					// Fill Sets
					sets.Rows.Add(new object[2] {(object)formState.CriteriaID,
													(object)i});

					// Fill SetItems	(Sample)					
					string[] items = (string[])rndSets[i];
					for (int j = 0; j < items.Length; j++) {
						setItems.Rows.Add(new object[3] {(object)i,
															(object)j,
															(object)items[j]});
					}
				}
							

				rndSetsDataSet.WriteXml(saveFileDialog1.FileName);
			}

		}



		private void loadSets() {
			
			// Show open diolog
			OpenFileDialog openFileDialog1 = new OpenFileDialog();

			//openFileDialog1.InitialDirectory = "c:\\" ;
			openFileDialog1.Filter = "RandomRat sets files (*.sets)|*.sets|RandomRat sample files (*.samp)|*.samp";
			openFileDialog1.FilterIndex = 1;
			openFileDialog1.RestoreDirectory = true ;

			if (openFileDialog1.ShowDialog() == DialogResult.OK) {
				
				rndSetsDataSet = new RndSetsDataSet();
				
				// Read in data
				rndSetsDataSet.ReadXml(openFileDialog1.FileName);

				// Hook up relationship
				rndSetsDataSet.Relations.Add(rndSetsDataSet.Tables["Criteria"].Columns["CriteriaID"], 
					rndSetsDataSet.Tables["Sets"].Columns["CriteriaID"]);

				rndSetsDataSet.Relations.Add(rndSetsDataSet.Tables["Criteria"].Columns["CriteriaID"], 
					rndSetsDataSet.Tables["Types"].Columns["CriteriaID"]);
				rndSetsDataSet.Relations.Add(rndSetsDataSet.Tables["Criteria"].Columns["CriteriaID"], 
					rndSetsDataSet.Tables["Patterns"].Columns["CriteriaID"]);
				
				rndSetsDataSet.Relations.Add(rndSetsDataSet.Tables["Sets"].Columns["SetID"], 
					rndSetsDataSet.Tables["SetItems"].Columns["SetID"]);


				// Set up view
				view = new DataView(rndSetsDataSet.SetItems);

				// Inishal filter
				maxSetID = rndSetsDataSet.Tables["Sets"].Rows.Count;
				setID = 1;
				


				// Set formState
				formState = new CriteriaFormState();

				DataTable criteria = rndSetsDataSet.Tables["Criteria"];
				DataTable types = rndSetsDataSet.Tables["Types"];
				DataTable patterns = rndSetsDataSet.Tables["Patterns"];

				// Get data from the criteria table
				int i = 0; 
				formState.Slots =			(string)criteria.Rows[i][1];
				formState.Sets =			(string)criteria.Rows[i][2];
				formState.SuccessionTol =	(string)criteria.Rows[i][3];
				formState.EveryOtherTol =	(string)criteria.Rows[i][4];
			
				formState.checkedSuccessionTol =	(bool)criteria.Rows[i][5];
				formState.checkedEveryOtherTol =	(bool)criteria.Rows[i][6];
				formState.checkedPatternRules =		(bool)criteria.Rows[i][7];
				formState.checkedForceEqualTypes =	(bool)criteria.Rows[i][8];

				// Get data from types
				ArrayList typesAL = new ArrayList();
				foreach (DataRow row in types.Rows) {
					typesAL.Add(row["type"]);
				}
				formState.Types = (string[])typesAL.ToArray(typeof(string));


				// Get data from patterns
				foreach (DataRow row in patterns.Rows) {
					formState.advancedPatternRules.Add(new int[2] {(int)row["Grouping"], (int)row["Tolerance"]});
				}


				// Do summary thing
				richTextBox1.Text = CriteriaFormState.GetSummary(formState, SummaryType.AbbreviatedNames, false);



				// Hookup to dataGrid
				dataGrid1.DataSource = view;

				numberBox1.Enabled = true;

				setUpColums();
			}
		}


		private void getSets() {
			rndSets = new ArrayList(rndSetsDataSet.Sets.Count);
			
			int setIndx;
			int slot;
			int slots = int.Parse((string)rndSetsDataSet.Tables["Criteria"].Rows[0]["Slots"]);

			foreach (DataRow setItem in  rndSetsDataSet.SetItems.Rows) {
				setIndx = (int)setItem["SetID"] - 1;
				slot = (int)setItem["Slot"] - 1;
				
				if (slot == 0) {
					rndSets.Add(new string[slots]);
				}

				((string[])rndSets[setIndx])[slot] = (string)setItem["Type"];
			}
		}





		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code

		private void InitializeComponent()
		{
			this.richTextBox1 = new System.Windows.Forms.RichTextBox();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.numberBox1 = new NumberBox();
			this.butLast = new System.Windows.Forms.Button();
			this.butNext = new System.Windows.Forms.Button();
			this.butBack = new System.Windows.Forms.Button();
			this.butFirst = new System.Windows.Forms.Button();
			this.dataGrid1 = new System.Windows.Forms.DataGrid();
			this.groupBox2 = new System.Windows.Forms.GroupBox();
			this.mainMenu1 = new System.Windows.Forms.MainMenu();
			this.menFile = new System.Windows.Forms.MenuItem();
			this.menFile_Open = new System.Windows.Forms.MenuItem();
			this.menuItem8 = new System.Windows.Forms.MenuItem();
			this.menFile_Print = new System.Windows.Forms.MenuItem();
			this.menFile_PrintPreview = new System.Windows.Forms.MenuItem();
			this.menuItem7 = new System.Windows.Forms.MenuItem();
			this.menFile_Close = new System.Windows.Forms.MenuItem();
			this.menView = new System.Windows.Forms.MenuItem();
			this.menView_ItemNumbers = new System.Windows.Forms.MenuItem();
			this.menView_Summary = new System.Windows.Forms.MenuItem();
			this.groupBox1.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
			this.groupBox2.SuspendLayout();
			this.SuspendLayout();
			// 
			// richTextBox1
			// 
			this.richTextBox1.Location = new System.Drawing.Point(12, 19);
			this.richTextBox1.Name = "richTextBox1";
			this.richTextBox1.ReadOnly = true;
			this.richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedVertical;
			this.richTextBox1.Size = new System.Drawing.Size(252, 321);
			this.richTextBox1.TabIndex = 2;
			this.richTextBox1.Text = "";
			this.richTextBox1.WordWrap = false;
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.numberBox1,
																					this.butLast,
																					this.butNext,
																					this.butBack,
																					this.butFirst,
																					this.dataGrid1});
			this.groupBox1.Location = new System.Drawing.Point(10, 7);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(230, 353);
			this.groupBox1.TabIndex = 8;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Sets";
			// 
			// numberBox1
			// 
			this.numberBox1.Enabled = false;
			this.numberBox1.Location = new System.Drawing.Point(92, 319);
			this.numberBox1.MaxLength = 9;
			this.numberBox1.Name = "numberBox1";
			this.numberBox1.Size = new System.Drawing.Size(44, 20);
			this.numberBox1.TabIndex = 13;
			this.numberBox1.Text = "";
			this.numberBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.numberBox1_KeyDown);
			this.numberBox1.Leave += new System.EventHandler(this.numberBox1_Leave);
			// 
			// butLast
			// 
			this.butLast.Enabled = false;
			this.butLast.Location = new System.Drawing.Point(180, 319);
			this.butLast.Name = "butLast";
			this.butLast.Size = new System.Drawing.Size(36, 23);
			this.butLast.TabIndex = 12;
			this.butLast.Text = ">>";
			this.butLast.Click += new System.EventHandler(this.butLast_Click);
			// 
			// butNext
			// 
			this.butNext.Enabled = false;
			this.butNext.Location = new System.Drawing.Point(140, 319);
			this.butNext.Name = "butNext";
			this.butNext.Size = new System.Drawing.Size(36, 23);
			this.butNext.TabIndex = 11;
			this.butNext.Text = ">";
			this.butNext.Click += new System.EventHandler(this.butNext_Click);
			// 
			// butBack
			// 
			this.butBack.Enabled = false;
			this.butBack.Location = new System.Drawing.Point(52, 319);
			this.butBack.Name = "butBack";
			this.butBack.Size = new System.Drawing.Size(36, 23);
			this.butBack.TabIndex = 10;
			this.butBack.Text = "<";
			this.butBack.Click += new System.EventHandler(this.butBack_Click);
			// 
			// butFirst
			// 
			this.butFirst.Enabled = false;
			this.butFirst.Location = new System.Drawing.Point(12, 319);
			this.butFirst.Name = "butFirst";
			this.butFirst.Size = new System.Drawing.Size(36, 23);
			this.butFirst.TabIndex = 9;
			this.butFirst.Text = "<<";
			this.butFirst.Click += new System.EventHandler(this.butFirst_Click);
			// 
			// dataGrid1
			// 
			this.dataGrid1.AllowSorting = false;
			this.dataGrid1.BackgroundColor = System.Drawing.SystemColors.Window;
			this.dataGrid1.CaptionVisible = false;
			this.dataGrid1.ColumnHeadersVisible = false;
			this.dataGrid1.DataMember = "";
			this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dataGrid1.Location = new System.Drawing.Point(12, 18);
			this.dataGrid1.Name = "dataGrid1";
			this.dataGrid1.ParentRowsVisible = false;
			this.dataGrid1.ReadOnly = true;
			this.dataGrid1.RowHeadersVisible = false;
			this.dataGrid1.Size = new System.Drawing.Size(204, 296);
			this.dataGrid1.TabIndex = 8;
			// 
			// groupBox2
			// 
			this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] {
																					this.richTextBox1});
			this.groupBox2.Location = new System.Drawing.Point(256, 8);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(276, 352);
			this.groupBox2.TabIndex = 9;
			this.groupBox2.TabStop = false;
			this.groupBox2.Text = "Summary";
			// 
			// mainMenu1
			// 
			this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menFile,
																					  this.menView});
			// 
			// menFile
			// 
			this.menFile.Index = 0;
			this.menFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					this.menFile_Open,
																					this.menuItem8,
																					this.menFile_Print,
																					this.menFile_PrintPreview,
																					this.menuItem7,
																					this.menFile_Close});
			this.menFile.Text = "&File";
			this.menFile.Popup += new System.EventHandler(this.menFile_Popup);
			// 
			// menFile_Open
			// 
			this.menFile_Open.Index = 0;
			this.menFile_Open.Text = "&Open";
			this.menFile_Open.Click += new System.EventHandler(this.menFile_Open_Click);
			// 
			// menuItem8
			// 
			this.menuItem8.Index = 1;
			this.menuItem8.Text = "-";
			// 
			// menFile_Print
			// 
			this.menFile_Print.Index = 2;
			this.menFile_Print.Text = "&Print";
			this.menFile_Print.Click += new System.EventHandler(this.menFile_Print_Click);
			// 
			// menFile_PrintPreview
			// 
			this.menFile_PrintPreview.Index = 3;
			this.menFile_PrintPreview.Text = "Print Pre&view";
			this.menFile_PrintPreview.Click += new System.EventHandler(this.menFile_PrintPreview_Click);
			// 
			// menuItem7
			// 
			this.menuItem7.Index = 4;
			this.menuItem7.Text = "-";
			// 
			// menFile_Close
			// 
			this.menFile_Close.Index = 5;
			this.menFile_Close.Text = "&Close";
			this.menFile_Close.Click += new System.EventHandler(this.menFile_Close_Click);
			// 
			// menView
			// 
			this.menView.Index = 1;
			this.menView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					this.menView_ItemNumbers,
																					this.menView_Summary});
			this.menView.Text = "&View";
			this.menView.Popup += new System.EventHandler(this.menView_Popup);
			// 
			// menView_ItemNumbers
			// 
			this.menView_ItemNumbers.Index = 0;
			this.menView_ItemNumbers.Text = "&Item numbers";
			this.menView_ItemNumbers.Click += new System.EventHandler(this.menView_ItemNumbers_Click);
			// 
			// menView_Summary
			// 
			this.menView_Summary.Checked = true;
			this.menView_Summary.Index = 1;
			this.menView_Summary.Text = "&Summary";
			this.menView_Summary.Click += new System.EventHandler(this.menView_Summary_Click);
			// 
			// SetsViewer
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(542, 371);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.groupBox2,
																		  this.groupBox1});
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.Menu = this.mainMenu1;
			this.MinimizeBox = false;
			this.Name = "SetsViewer";
			this.ShowInTaskbar = false;
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
			this.Text = "Sets Viewer";
			this.groupBox1.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
			this.groupBox2.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		
		
		private void validateButtons() {
			butNext.Enabled = setID != maxSetID;
			butBack.Enabled = setID != 1;

            butLast.Enabled = setID != maxSetID;
			butFirst.Enabled = setID != 1;
		}


		private void menFile_Open_Click(object sender, System.EventArgs e) {
			loadSets();
		}

		private void butNext_Click(object sender, System.EventArgs e) {
			setID++;
		}

		private void butBack_Click(object sender, System.EventArgs e) {
			setID--;
		}

		private void butFirst_Click(object sender, System.EventArgs e) {
			setID = 1;
		}

		private void butLast_Click(object sender, System.EventArgs e) {
			setID = maxSetID;
		}

		private void menView_ItemNumbers_Click(object sender, System.EventArgs e) {
			viewItemNumber = !viewItemNumber;
		}

		private void menView_Popup(object sender, System.EventArgs e) {
			menView_ItemNumbers.Checked = viewItemNumber;
		}

		private void numberBox1_Leave(object sender, System.EventArgs e) {
			numberBox1_UpdateView();
		}

		private void numberBox1_UpdateView() {
			int setBox = -1;
			try {
				setBox = int.Parse(numberBox1.Text);
			} catch {}

			if (setBox == -1 || setBox == 0) {
				setID = 1;
			} else if (setBox > maxSetID) {
				setID = maxSetID;
			} else {
				setID = setBox;
			}
	
			numberBox1.SelectAll();
		}

		private void numberBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) {
			if (e.KeyCode == Keys.Enter) {
				numberBox1_UpdateView();
			}
		}

		private void menFile_Close_Click(object sender, System.EventArgs e) {
			this.Close();
		}

		private void menView_Summary_Click(object sender, System.EventArgs e) {
			if (menView_Summary.Checked) {
				this.Width = formWidthWithoutSum;
			} else {
				this.Width = formSWidthWithSm;
			}
			menView_Summary.Checked = !menView_Summary.Checked;
		}

		private void menFile_Print_Click(object sender, System.EventArgs e) {
			if (rndSets == null) getSets();
			RandomSetPrinter rndSetPrinter = new RandomSetPrinter(rndSets, formState.ToSetArguments(), this);
            rndSetPrinter.Print(RandomSetPrintMode.PrintWithDiolog, this);
		}

		private void menFile_PrintPreview_Click(object sender, System.EventArgs e) {
			if (rndSets == null) getSets();
			RandomSetPrinter rndSetPrinter = new RandomSetPrinter(rndSets, formState.ToSetArguments(), this);
            rndSetPrinter.Print(RandomSetPrintMode.PrintPreview, this);
		}

		private void menFile_Popup(object sender, System.EventArgs e) {
			if (formState == null) {
				menFile_Print.Enabled = false;
				menFile_PrintPreview.Enabled = false;
			} else {
				menFile_Print.Enabled = true;
				menFile_PrintPreview.Enabled = true;
			}
		}




	}
}
